﻿using System;
using System.Collections.Generic;
using System.Text;
using Wjtour.Common;
using Wjtour.Domain;
using System.Linq;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;

namespace Wjtour.BLL
{
    public class articletype_bll : base_dll
    {
        public PaginationData<Wjtour.Domain.dto.articletype_num> GetList(string q, int page = 0, int pagesize = 20)
        {
            string where = " ";
            if (!string.IsNullOrEmpty(q))
                where += " and a.title like '%" + Utility.GetSafeSql(q) + "%' ";
            string sql = string.Format(@"select at.*,COUNT(a.id) articlenum from articletype at
                left join article a on at.id=a.cid
                where at.tag='article'
                group by at.id,at.pid,at.sort,at.sys,at.tag,at.title,at.addtime", where);
            PaginationData<Wjtour.Domain.dto.articletype_num> data = GetPaginationData<Wjtour.Domain.dto.articletype_num>(sql, page, pagesize);
            return data;
        }

        public Wjtour.Domain.articletype Load(int id)
        {
            string sql = "select * from articletype where id=" + id;
            return DbAccess.GetObjects<Wjtour.Domain.articletype>(sql).FirstOrDefault();
        }

        public bool Save(Wjtour.Domain.articletype entity)
        {
            string sql = "";

            DbCommand cmd = DbAccess.CreateCommand();

            if (entity.id > 0)
            {
                sql = @"UPDATE [articletype] SET 
            [pid] = @pid,
            [title] = @title,
            [sort] = @sort,
            [tag] = @tag,
            [addtime] = @addtime,
            [sys] = @sys
             WHERE id=@id";
                DbAccess.AddInParameter(cmd, "@id", DbType.Int32, entity.id);

            }
            else
            {
                sql = @"INSERT INTO [articletype]( 
                [pid],[title],[sort],[tag],[addtime],[sys])VALUES(
                @pid,@title,@sort,@tag,@addtime,@sys)";
            }
            DbAccess.AddInParameter(cmd, "@pid", DbType.Int32, entity.pid);
            DbAccess.AddInParameter(cmd, "@title", DbType.String, entity.title);
            DbAccess.AddInParameter(cmd, "@sort", DbType.Int32, entity.sort);
            DbAccess.AddInParameter(cmd, "@tag", DbType.String, entity.tag);
            DbAccess.AddInParameter(cmd, "@addtime", DbType.DateTime, entity.addtime);
            DbAccess.AddInParameter(cmd, "@sys", DbType.Int16, entity.sys);
            cmd.CommandText = sql;
            cmd.CommandType = System.Data.CommandType.Text;
            return DbAccess.ExecuteNonQuery(cmd) > 0;

        }


        public int BatchDelete(string ids)
        {
            string sql = "delete from articletype where id in(" + ids + ")";
            return DbAccess.ExecuteNonQuery(sql);
        }
    }
}
